<%--suppress ALL --%>
<%@ page import="com.example.dao.ProductDao" %>
<%@ page import="com.example.domain.Product" %>
<%@ page import="com.example.util.DBUtil" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="org.apache.commons.fileupload.FileItem" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.io.File" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    // 检查是否为POST请求
    if (!"POST".equalsIgnoreCase(request.getMethod())) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    request.setCharacterEncoding("UTF-8");
    
    // 检查是否为multipart请求
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        response.sendRedirect("product_list.jsp?error=无效的请求");
        return;
    }

    // 初始化变量
    int productId = 0;
    String productName = "";
    double price = 0.0;
    double salePrice = 0.0;
    int typeId = 0;
    int status = 0;
    int isTop = 0;
    String intro = "";
    String logoPath = "";
    String idxPath = "";
    boolean updateLogo = false;
    boolean updateIdx = false;

    try {
        // 创建工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        
        // 创建文件上传处理器
        ServletFileUpload upload = new ServletFileUpload(factory);
        
        // 解析请求
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        
        while (iter.hasNext()) {
            FileItem item = iter.next();
            
            if (item.isFormField()) {
                // 处理普通表单字段
                String fieldName = item.getFieldName();
                String fieldValue = item.getString("UTF-8");
                
                switch (fieldName) {
                    case "id":
                        productId = Integer.parseInt(fieldValue);
                        break;
                    case "product_name":
                        productName = fieldValue;
                        break;
                    case "price":
                        price = Double.parseDouble(fieldValue);
                        break;
                    case "sale_price":
                        salePrice = Double.parseDouble(fieldValue);
                        break;
                    case "type_id":
                        typeId = Integer.parseInt(fieldValue);
                        break;
                    case "status":
                        status = Integer.parseInt(fieldValue);
                        break;
                    case "is_top":
                        isTop = Integer.parseInt(fieldValue);
                        break;
                    case "intro":
                        intro = fieldValue;
                        break;
                }
            } else {
                // 处理文件上传字段
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                
                if (fileName != null && !fileName.isEmpty()) {
                    // 获取文件扩展名
                    String fileExtension = "";
                    int dotIndex = fileName.lastIndexOf(".");
                    if (dotIndex > 0) {
                        fileExtension = fileName.substring(dotIndex).toLowerCase();
                    }
                    
                    // 验证文件类型
                    if (!fileExtension.matches("\\.(jpg|jpeg|png|gif)$")) {
                        response.sendRedirect("product_list.jsp?error=只支持JPG、JPEG、PNG、GIF格式的图片");
                        return;
                    }
                    
                    // 生成唯一文件名
                    String uniqueFileName = System.currentTimeMillis() + "_" + Math.round(Math.random() * 1000) + fileExtension;
                    
                    // 设置保存路径 - 使用专门的商品图片目录
                    String uploadPath = application.getRealPath("/") + "uploads" + File.separator + "products";
                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }
                    
                    // 保存文件
                    File uploadedFile = new File(uploadPath + File.separator + uniqueFileName);
                    item.write(uploadedFile);
                    
                    // 设置文件路径（相对于Web应用根目录）
                    String relativePath = "uploads/products/" + uniqueFileName;
                    
                    if ("logo".equals(fieldName)) {
                        logoPath = relativePath;
                        updateLogo = true;
                    }
                }
            }
        }
        
        // 验证必填字段
        if (productId <= 0 || productName.isEmpty() || price <= 0) {
            response.sendRedirect("product_list.jsp?error=商品ID、名称和价格是必填项");
            return;
        }
        
        // 获取现有商品信息
        ProductDao productDao = new ProductDao();
        Product product = productDao.getProductById(productId).orElse(null);
        if (product == null) {
            response.sendRedirect("product_list.jsp?error=商品不存在");
            return;
        }
        
        // 更新商品对象
        product.setProduct_name(productName);
        product.setPrice(price);
        product.setSale_price(salePrice);
        product.setType_id(typeId);
        product.setStatus(status);
        product.setIs_top(isTop);
        product.setIntro(intro);
        
        // 只有当上传了新文件时才更新路径
        if (updateLogo) {
            product.setLogo(logoPath);
        }
        if (updateIdx) {
            product.setIdx(idxPath);
        }
        
        // 更新数据库
        productDao.updateProduct(product);
        
        // 重定向到商品列表页面
        response.sendRedirect("product_list.jsp?message=商品更新成功");
    } catch (Exception e) {
        response.sendRedirect("product_list.jsp?error=更新商品失败: " + e.getMessage());
    }
%>